require 'rubygems'
require 'hpricot'
require 'net/http'
require 'net/https'
require 'uri'

 # to_hash
  class String
     def to_hash(seperation='&', assignment='=')
       hash = Hash.new
       self.split(seperation).each do |elemement|
         pieces = elemement.split(assignment)
         hash[pieces[0]] = pieces[1]
       end
       hash.delete_if { |key, value| value.nil? }
     end
  end

# This module is used to connect Movistar CopiAgenda Service API
# The common way to use is to call the get_contacts function, and
# a Contact objects array will be returned.

module CopiAgenda
  
  class Contact
    attr_accessor :name, :surname, :phonenumber
    # Crear el objeto
    def initialize(nombre, tfno, surname = nil)
      @name=nombre.to_s unless nombre.nil?
      @phonenumber=tfno.to_s unless tfno.nil?
      @surname=surname.to_s unless surname.nil?
    end
  end

  #################################################
  # 0  Title       "" 
  # 1  FirstName   "" 
  # 2  FirstName 2 ""
  # 3  Surname     ""
  # 4  Suffix      ""
  # 5  Nickname    ""
  # 6  email 2     "" 
  # 7  email       ""  
  # 8  email 3     ""  
  # 9  Business phone  ""  
  # 10 Business Fax    ""  
  # 11 Mobile Phone    ""  
  # 12 Pager           ""  
  # 13 Another phone   ""  
  # 14 Personal phone  ""  
  # 15 Home Fax        ""  
  # 16 Home Phone 2    ""  
  # 17 Buscapersonas particular  ""  
  # 18 Business Phone 2          "" 
  # 19 IM                        ""  
  # 20 Yahoo  ""     
  # 21 MSN ""  
  # 22 AIM ""  
  # 23 Puesto ""  
  # 24 Organización ""  
  # 25 Department ""  
  # 26 Calle del trabajo 2 ""  
  # 27 Calle del trabajo 3 ""  
  # 28 Calle del trabajo ""  
  # 29 Ciudad de trabajo ""  
  # 30 Provincia o estado de trabajo ""  
  # 31 Código postal del trabajo ""  
  # 32 País de trabajo ""  
  # 33 Página Web ""  
  # 34 Home Street 2 ""  
  # 35 Home Street 3 ""  
  # 36 Home Street ""  
  # 37 Home City ""  
  # 38 Home State ""  
  # 39 Home Postal Code ""  
  # 40 Home Country ""  
  # 41 Página Web personal ""  
  # 42 Otra calle 2 ""  
  # 43 Otra calle 3 ""  
  # 44 Otra calle ""  
  # 45 Otra ciudad ""  
  # 46 Otra provincia o estado ""  
  # 47 Otro código postal ""  
  # 48 Otro país ""  
  # 49 Otro sitio Web ""  
  # 50 Atributo de teléfono predeterminado ""  
  # 51 Atributo de correo electrónico predeterminado ""  
  # 52 Birthday ""  
  # 53 Notes ""  
  # 54 Categorías  "SIM"

  def get_data(login, pass)
    # urlS 
    url = "copiagenda.movistar.es"
    url_login = "/cp/ps/Main/login/Agenda"
    url_verification = "/cp/ps/Main/login/Verificacion?d=movistar.es"
    url_token = "/cp/ps/Main/login/Authenticate"
    url_ask = "/cp/ps/PSPab/preferences/ExportContacts?d=movistar.es&c=yes"
  
    ## iniciamos conexiÃ³n
    http = Net::HTTP.new(url, 443)
    http.use_ssl = true
  
    ## nos logueamos
    data = "TM_ACTION=LOGIN&TM_LOGIN=#{login}&TM_PASSWORD=#{pass}" 
    headers = {
      'User-Agent'    => 'Mozilla/4.0',
      'Content-Type'  => 'application/x-www-form-urlencoded',
      'Connection'    => 'Keep-Alive'
    }
    resp, data = http.post(url_login, data, headers)
    cookie = resp.response['set-cookie']
    cookie = cookie.sub(" Path=/, "," ")
    cookie = cookie.sub("; Domain=.movistar.es; Path=/","")
    cookie = cookie.rstrip
  
    ## conseguimos con la cookie el token de sesiÃ³n
    headers = {
      'Cookie'        => cookie,
      'User-Agent'    => 'Mozilla/4.0',
      'Content-Type'  => 'application/x-www-form-urlencoded',
      'Connection'    => 'Keep-Alive'
    }
    resp, data = http.get(url_verification, headers)
  
    # pasamos la respuesta por hpricot para buscar la password codificada
    doc = Hpricot(resp.response.body)
   
    passCode = doc.search("//input[@name='password']")
    
    if passCode.nil? or passCode.empty?
      pp "retorno nil"
      return nil
    else
      pp "sigo"
    end
   #if passCode.first.nil? or passCode.first.empty?

   #   pp "retorno nil"
    #  return nil
    #else
    #  pp "sigo"
    #end*/
    
    passCode = passCode.first.attributes['value']
  
    data = "password=#{passCode}&u=#{login}&d=movistar.es"
    headers = {
      'Cookie'          => cookie,
      'User-Agent'      => 'Mozilla/4.0',
      'Accept-Encoding' => 'gzip, deflate', 
      'Host'            => 'copiagenda.movistar.es', 
      'Referer'         => 'https://copiagenda.movistar.es/cp/ps/Main/login/Verificacion?d=movistar.es',
      'Content-Type'    => 'application/x-www-form-urlencoded',
      'Connection'      => 'Keep-Alive'
    }
  
    resp, data = http.post(url_token, data, headers)
    doc = Hpricot(resp.response.body)
    
    frameSrc = doc.search("//frame[@name='BrandHeader']").first.attributes["src"].to_hash
    token = frameSrc.fetch("t")
  
    data = "fileFormat=TEXT&charset=UTF8&delimiter=TAB"
    headers = {
      'Cookie'          => cookie,
      'User-Agent'      => 'Mozilla/4.0',
      'Accept-Encoding' => 'gzip, deflate',
      'Host'            => 'copiagenda.movistar.es', 
      'Referer'         => 'https://copiagenda.movistar.es/cp/ps/Main/login/Verificacion?d=movistar.es',
      'Content-Type'    => 'application/x-www-form-urlencoded',
      'Accept-Language' => 'es',
      'Cache-Control'   => 'no-cache',
      'Connection'      => 'Keep-Alive'
    }
    resp, data = http.post("#{url_ask}&u=#{login}&t=#{token}", data, headers)
    
    doc = Hpricot(resp.response.body)
    # eliminamos script tag y comentarios
    doc.search("script").remove  
    doc.search("*").map{|e| e.swap("") if e.comment?}
    csv = doc.to_s
  end
  
  
  def parse_contacts(csv)
    contactos = []
    csv = csv.split("\r")
    csv.each_with_index do |row, index|
      if index > 0 && row.split("\"\t\"").size > 1
        contactos << row.split("\"\t\"") 
      end
    end
    contactos
  end
  
  def get_contacts(login, pass)
    data = get_data(login, pass)
    if data.nil?
      pp "get_contacts retorna nil"
      return nil
    end
    contacts = parse_contacts(data)
    misContactos = []
    contacts.each do |contact|
      contact = Contact.new(contact[1], contact[18], contact[3])
      misContactos.push(contact)
    end
    misContactos
  end

end # module
